@file:Suppress("unused")

package com.hjh.tool.extension

import android.graphics.Bitmap
import android.util.Base64
import androidx.core.graphics.scale
import com.elvishew.xlog.XLog
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import kotlin.math.max
import kotlin.onFailure


/**
 * @author： hjh
 * @createDate： 2025/5/8 10:28
 * @description：
 * @qq： 3472903821
 * @version: 1.0
 */

fun Bitmap.toBase64(
    format: Bitmap.CompressFormat = Bitmap.CompressFormat.JPEG,
    quality: Int = 100
): String {
    runCatching {
        val byteArrayOutputStream = ByteArrayOutputStream()
        this.compress(format, quality, byteArrayOutputStream)
        val byteArray = byteArrayOutputStream.toByteArray()
        return Base64.encodeToString(byteArray, Base64.DEFAULT)
    }.onFailure {
        return ""
    }
    return ""
}

// Bitmap扩展函数 - 按最大边长缩放
fun Bitmap.scaleToMax(maxSize: Int): Bitmap {
    val scale = maxSize.toFloat() / max(width, height)
    return if (scale < 1) {
        this.scale((width * scale).toInt(), (height * scale).toInt())
    } else {
        this
    }
}

fun Bitmap.toFile(dir: String, name: String): File? {
    if (!dir.isFileExist()) {
        XLog.e("文件夹不存在或创建失败")
        return null
    } else {
        val saveFile = File(dir, name)
        return try {
            val fos = FileOutputStream(saveFile)
            this.compress(Bitmap.CompressFormat.JPEG, 80, fos)
            fos.flush()
            fos.close()
            saveFile
        } catch (e: IOException) {
            XLog.e(e.message)
            null
        }
    }
}